package org.example.tlias.filter;

import jakarta.servlet.*;
import jakarta.servlet.annotation.WebFilter;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.example.tlias.utils.JwtUtils;

import java.io.IOException;
import java.net.http.HttpRequest;
import java.net.http.HttpResponse;


//@WebFilter("/*")
public class JwtFilter implements Filter {
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {

        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        //1.获取请求路径
        String path = request.getRequestURI().toString();//emps/login

        //2。判断是否是登录请求，是放行，否则进行JWT验证
        if (path.contains("login")) {
            filterChain.doFilter(request, response);
        } else {
            //获取请求头中的token
            String token = request.getHeader("token");
            //判断token是否存在
            if (token == null || token.isEmpty()) {
                response.setStatus(401);
                return;
            }
            try {
                if (JwtUtils.parseJwt(token, "123456") != null) {
                    filterChain.doFilter(request, response);
                } else {
                    response.setStatus(401);
                }
            } catch (Exception e) {
                response.setStatus(401);
            }
        }

        //4.判断token是否存在，存在则进行JWT验证，否则返回401
        //校验通过，放行

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
